<?php

namespace app\api\controller;

use app\api\model\UserModel;
use app\api\validate\UserValidate;
use app\BaseController;

class User extends BaseController
{
    //注册
    public function register(){
        // 接收数据
        $data = input('post.');
        $validate = new UserValidate();
        $result = $validate->scene('register')->check($data);
        if(!$result){
            return error($validate->getError());
        }

        // 判断账号是否已被注册
        $account = UserModel::where('mobile',$data['mobile'])->find();
        if ($account) {
            echo '该手机号已被注册';
        }

        // 加密密码存入数据库
        $randStr = createRandStr(8);
        $data['password'] = md5($data['password'].$randStr);
        $data['salt'] = $randStr;
        $user = UserModel::create($data);
        if($user){
            return success('注册成功');
        }else{
            return error('注册失败');
        }
    }

    //登录
    public function login(){
        // 接收数据
        $data = input('post.');
        $validate = new UserValidate();
        $result = $validate->scene('login')->check($data);
        if(!$result){
            return error($validate->getError());
        }

        // 登录
        $user = UserModel::where('mobile',$data['mobile'])->find();
        if(!$user){
            return error('该账号不存在');
        }
        if(md5($data['password'].$user['salt']) != $user['password']){
            return error('密码错误');
        }
        return success('登录成功');
    }
}